package com.xiaoyu.tool.configuration.wx;


import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.WxMpKefuService;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;

/**
 *
 * 配置微信公众号sdk并且重写sdk的configStorage实现access_token两小时内不过期造成重复刷新问题,可用于分布式
 *
 * */
@Slf4j
@Configuration
@EnableConfigurationProperties(WxMpProperty.class)
public class WxMpConfiguration {

    private final RedisTemplate<String, String> redisTemplate;

    private final WxMpProperty wxMpProperty;

    public WxMpConfiguration(RedisTemplate<String, String> redisTemplate, WxMpProperty wxMpProperty) {
        this.redisTemplate = redisTemplate;
        this.wxMpProperty = wxMpProperty;
    }

    @Bean
    public WxMpService wxMpService(){
        WxMpSpringRedisConfigStorage configStorage = new WxMpSpringRedisConfigStorage(redisTemplate);
        configStorage.setAppId(wxMpProperty.getAppId());
        configStorage.setSecret(wxMpProperty.getAppSecret());
        configStorage.setToken(wxMpProperty.getToken());
        WxMpService wxMpService = new WxMpServiceImpl();
        wxMpService.setWxMpConfigStorage(configStorage);
        return wxMpService;
    }

    @Bean
    public WxMpKefuService wxMpKefuService(@Qualifier("wxMpService") WxMpService wxMpService){
        return wxMpService.getKefuService();
    }

}
